﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Microsoft.SqlServer.Management.Smo;
using BookStore.Solution.Configurations;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using System.IO;

namespace BookStore.Solution.Presentation
{
    public partial class frmRestore : DevComponents.DotNetBar.OfficeForm
    {
        public frmRestore()
        {
            InitializeComponent();
            this.MaximumSize = this.MinimumSize = this.Size;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            string sConnect = Configs.DbPassport;
            if (txtFolder.Text != "")
            {
                try
                {
                    txtFolder.Enabled = cbFileName.Enabled = btnFolder.Enabled = btnRestore.Enabled = btnCancel.Enabled = false;
                    //ngắt kết nối cơ sở dữ liệu
                    using (SqlConnection cnn = new SqlConnection(sConnect))
                    {
                        SqlCommand command = cnn.CreateCommand();
                        command.CommandText = "alter Database " + Configs.Database + " Set OFFLINE with ROLLBACK IMMEDIATE alter Database " + Configs.Database + " Set ONLINE";
                        cnn.Open();
                        command.ExecuteNonQuery();
                        cnn.Close();
                    }
                    ServerConnection connection = new ServerConnection(Configs.Server);

                    Server databaseServer = new Server(connection);

                    //Create an instance of the restore object.   
                    Restore res = new Restore();

                    //The name of the database that will be restored.
                    res.Database = Configs.Database;

                    //Restore options      
                    res.Action = RestoreActionType.Database;
                    //Name of backup file
                    res.Devices.AddDevice(txtFolder.Text + @"\" + cbFileName.Text, DeviceType.File);
                    res.ReplaceDatabase = true;
                    res.PercentComplete += new PercentCompleteEventHandler(bkp_PercentComplete);
                    //Execute the restore   
                    res.SqlRestore(databaseServer);
                    databaseServer.Refresh();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Phục hồi dữ liệu thất bại:\n" + ex.Message, "Thông báo");
                    btnCancel.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn thư mục", "Thông báo");
                btnCancel.Enabled = true;
            }
        }

        void bkp_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            this.pbProgress.Value = e.Percent;
            this.pbProgress.Text = e.Percent + "%";
            if (e.Percent == 100)
            {
                MessageBox.Show("Phục hồi dữ liệu thành công", "Thông báo");
                btnCancel.Enabled = true;
            }
        }


        private void frmRestore_Load(object sender, EventArgs e)
        {

        }
        
        private void btnFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtFolder.Text = folderBrowserDialog.SelectedPath;
                cbFileName.Items.Clear();

                DirectoryInfo curFolder = new DirectoryInfo(txtFolder.Text);
                List<FileInfo> files = new List<FileInfo>();
                foreach (FileInfo file in curFolder.GetFiles())
                {
                    string[] t = file.FullName.Split('.');
                    if (t[t.Length - 1].ToLower() == "bak")
                        files.Add(file);
                }
                if (files.Count == 0)
                {
                    MessageBox.Show("Không tìm thấy file phục hồi nào trong thư mục này", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                files.Sort(delegate(FileInfo X, FileInfo Y)
                {
                    return Y.CreationTime.CompareTo(X.CreationTime);
                }
                );

                foreach (FileInfo f in files)
                    cbFileName.Items.Add(f.Name);

                if (cbFileName.Items.Count > 0)
                    cbFileName.SelectedIndex = 0;
            }
        }
    }
}